package cn.thornbird.orgsync.repository.specification;

import cn.thornbird.orgsync.entity.Task;
import cn.thornbird.orgsync.vo.request.TaskQueryRequest;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@AllArgsConstructor
public class TaskSpecification extends BaseSpecification<Task> {

    private static final long serialVersionUID = -8013632857088981311L;

    private final TaskQueryRequest taskQueryRequest;

    @Override
    public Predicate toPredicate(@NotNull Root<Task> root, @NotNull CriteriaQuery<?> query,
                                 @NotNull CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = new ArrayList<>();
        List<String> fields = Arrays.asList("title");
        predicates.add(toKeywordPredicate(taskQueryRequest.getKeyword(), fields, root, criteriaBuilder));
        if (!StringUtils.isEmpty(taskQueryRequest.getCompanyId())) {
            predicates.add(criteriaBuilder.or(
                    criteriaBuilder.equal(root.get("sourceCompanyId"), taskQueryRequest.getCompanyId()),
                    criteriaBuilder.equal(root.get("targetCompanyId"), taskQueryRequest.getCompanyId())
            ));
        }
        if (taskQueryRequest.getAppType() != null) {
            predicates.add(criteriaBuilder.or(
                    criteriaBuilder.equal(root.get("sourceAppType"), taskQueryRequest.getAppType()),
                    criteriaBuilder.equal(root.get("targetAppType"), taskQueryRequest.getAppType())
            ));
        }
        if (taskQueryRequest.getActive() != null) {
            predicates.add(criteriaBuilder.equal(root.get("active"), taskQueryRequest.getActive()));
        }
        if (taskQueryRequest.getFrequency() != null) {
            predicates.add(criteriaBuilder.equal(root.get("frequency"), taskQueryRequest.getFrequency()));
        }
        if (taskQueryRequest.getLastExecuteStatus() != null) {
            predicates.add(criteriaBuilder.equal(root.get("lastExecuteStatus"),
                    taskQueryRequest.getLastExecuteStatus()));
        }
        if (!StringUtils.isEmpty(taskQueryRequest.getUserId())) {
            predicates.add(criteriaBuilder.equal(root.get("userId"), taskQueryRequest.getUserId()));
        }
        return toPredicate(criteriaBuilder, predicates);
    }

}
